package com.mingtu.guards.fragment;

import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.base.BaseFragment;
import com.mingtu.common.callback.StringDialogCallback;
import com.hjq.gson.factory.GsonFactory;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.IntentUtils;
import com.mingtu.common.utils.MyUtills;
import com.mingtu.common.utils.SpacesItemDecoration;
import com.mingtu.common.view.EmptyDataLayout;
import com.mingtu.common.viewpager.LazyViewPager.LazyFragmentPagerAdapter;
import com.mingtu.guards.R;
import com.mingtu.guards.activity.SendTaskDetailsActivity;
import com.mingtu.guards.adapter.SendTaskAdapter;
import com.mingtu.guards.bean.TaskListBean;
import com.mingtu.guards.utils.MyConstant;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;

import static com.mingtu.guards.utils.MyConstant.ItemDecorationSpaces;


public class FinishedFragment extends BaseFragment implements LazyFragmentPagerAdapter.Laziable {


    @BindView(R.id.recycler)
    RecyclerView recycler;
    @BindView(R.id.srl_up)
    SmartRefreshLayout srlUp;
    @BindView(R.id.empty_layout)
    EmptyDataLayout emptyLayout;
    private List<TaskListBean.PageBean.ListBean> DataBean = new ArrayList<>();
    private int currentPage = 1;
    private boolean isLoadMore = true;
    private SendTaskAdapter sendTaskAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_finished;
    }

    @Override
    protected void initData() {
        LinearLayoutManager manager1 = new LinearLayoutManager(context);
        recycler.setLayoutManager(manager1);
        recycler.addItemDecoration(new SpacesItemDecoration(0, 0, ItemDecorationSpaces, ItemDecorationSpaces, ItemDecorationSpaces));

        sendTaskAdapter = new SendTaskAdapter(context, true);
        recycler.setAdapter(sendTaskAdapter);
        sendTaskAdapter.setOnItemClickListener(new SendTaskAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                TaskListBean.PageBean.ListBean listBean = DataBean.get(position);
                String taskId = listBean.getId() + "";

                if (!StringUtils.isEmpty(taskId)) {
                    Bundle bundle = new Bundle();
                    bundle.putString("taskId", taskId);
                    IntentUtils.getInstance().readyGo(getActivity(), SendTaskDetailsActivity.class, bundle);
                } else {
                    ToastUtils.showLong(getResources().getString(R.string.data_error));
                }

            }
        });
        initListener();
    }

    @Override
    protected void initView(View view) {

    }

    @Override
    protected void getData() {
        getTaskList(1);
    }

    private void initListener() {
        initPullRefresh();//刷新
        initLoadMoreListener();//加载更多
    }

    private void initPullRefresh() {
        srlUp.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white);
        srlUp.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                srlUp.finishRefresh(Constant.REFRESH_TIME);
                srlUp.setNoMoreData(false);
                currentPage = 1;
                getTaskList(1);
            }
        });
    }

    private void initLoadMoreListener() {
        srlUp.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isLoadMore) {
                    currentPage = MyUtills.loadPage(DataBean, Constant.PAGE_SIZE);
                    getTaskList(currentPage);
                }
                srlUp.finishLoadMore(Constant.LOADMORE_TIME);
            }
        });

    }

    /**
     * 下发任务列表
     */
    private void getTaskList(int pageNum) {
        if (pageNum == 1) {
            currentPage = 1;
        }
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("curPage", pageNum);
        hashMap.put("pageSize", Constant.PAGE_SIZE);
        hashMap.put("status", 1);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_SEND_TASK_LIST)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(getActivity()) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {

                            TaskListBean taskListBean = null;
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                taskListBean = new TaskListBean();
                                taskListBean = gson.fromJson(result, TaskListBean.class);
                                List<TaskListBean.PageBean.ListBean> dataBeans = taskListBean.getPage().getList();

                                try {
                                    emptyLayout.setIsShowView(false);
                                    recycler.setVisibility(View.VISIBLE);

                                    if (dataBeans != null) {

                                        isLoadMore = dataBeans.size() > 0 && dataBeans.size() % Constant.PAGE_SIZE == 0 ? true : false;
                                        if (!isLoadMore) {
                                            if (currentPage > 1) {
                                                ToastUtils.showLong(getResources().getString(R.string.text_no_more_data));
                                            } else {
                                                if (dataBeans.size() == 0) {
                                                    //显示占位图
                                                    emptyLayout.setIsShowView(true);
                                                    recycler.setVisibility(View.GONE);
                                                }

                                            }
                                        }

                                        //当是第一页的时候先清空数组，防止下拉操作的时候加载重复数据
                                        if (currentPage == 1) {
                                            sendTaskAdapter.clearData();
                                        }
                                        DataBean.addAll(dataBeans);
                                        sendTaskAdapter.upData(DataBean);

                                    } else {
                                        if (currentPage == 1) {
                                            //显示占位图
                                            recycler.setVisibility(View.GONE);
                                            emptyLayout.setIsShowView(true);
                                        }
                                    }

                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            } catch (JsonSyntaxException e) {

                                e.printStackTrace();
                                isLoadMore = false;
                                emptyLayout.setIsShowView(true);
                                recycler.setVisibility(View.GONE);
                                ToastUtils.showLong(getResources().getString(R.string.text_json_error));

                            }


                        }
                    }
                });
    }

}